const express = require('express');
const router = express.Router();
const fs = require('fs');
const { db } = require('../app');

// 获取系统设置
router.get('/', (req, res) => {
    if (!req.session.user || req.session.user.role !== 'admin') {
        return res.status(403).json({ error: '没有权限' });
    }

    db.all('SELECT key, value FROM settings', (err, settings) => {
        if (err) {
            return res.status(500).json({ error: '获取设置失败' });
        }

        // 转换为键值对对象
        const settingsObj = {};
        settings.forEach(setting => {
            settingsObj[setting.key] = setting.value;
        });

        res.json({ success: true, settings: settingsObj });
    });
});

// 更新系统设置
router.put('/', (req, res) => {
    if (!req.session.user || req.session.user.role !== 'admin') {
        return res.status(403).json({ error: '没有权限' });
    }

    const { panel_name, panel_ip, require_email_verification, smtp_host, smtp_port, smtp_user, smtp_pass, smtp_secure, smtp_tls } = req.body;

    // 更新设置
    const updates = [];
    const params = [];

    if (panel_name !== undefined) {
        updates.push('(key, value) VALUES (?, ?)');
        params.push('panel_name', panel_name);
    }
    if (panel_ip !== undefined) {
        updates.push('(key, value) VALUES (?, ?)');
        params.push('panel_ip', panel_ip);
    }
    if (require_email_verification !== undefined) {
        updates.push('(key, value) VALUES (?, ?)');
        params.push('require_email_verification', require_email_verification.toString());
    }
    if (smtp_host !== undefined) {
        updates.push('(key, value) VALUES (?, ?)');
        params.push('smtp_host', smtp_host);
    }
    if (smtp_port !== undefined) {
        updates.push('(key, value) VALUES (?, ?)');
        params.push('smtp_port', smtp_port.toString());
    }
    if (smtp_user !== undefined) {
        updates.push('(key, value) VALUES (?, ?)');
        params.push('smtp_user', smtp_user);
    }
    if (smtp_pass !== undefined) {
        updates.push('(key, value) VALUES (?, ?)');
        params.push('smtp_pass', smtp_pass);
    }
    if (smtp_secure !== undefined) {
        updates.push('(key, value) VALUES (?, ?)');
        params.push('smtp_secure', smtp_secure.toString());
    }
    if (smtp_tls !== undefined) {
        updates.push('(key, value) VALUES (?, ?)');
        params.push('smtp_tls', smtp_tls.toString());
    }

    if (updates.length === 0) {
        return res.status(400).json({ error: '没有要更新的设置' });
    }

    // 使用REPLACE语句更新或插入设置
    const query = updates.map(() => 'REPLACE INTO settings (key, value) VALUES (?, ?)').join('; ');
    
    db.serialize(() => {
        updates.forEach((update, index) => {
            const baseIndex = index * 2;
            db.run('REPLACE INTO settings (key, value) VALUES (?, ?)', 
                [params[baseIndex], params[baseIndex + 1]]);
        });
    });

    res.json({ success: true, message: '设置更新成功' });
});

// 测试邮件配置
router.post('/test-email', (req, res) => {
    if (!req.session.user || req.session.user.role !== 'admin') {
        return res.status(403).json({ error: '没有权限' });
    }

    const { smtp_host, smtp_port, smtp_user, smtp_pass, smtp_secure, smtp_tls, test_email } = req.body;

    if (!smtp_host || !smtp_port || !smtp_user || !smtp_pass || !test_email) {
        return res.status(400).json({ error: '所有邮件配置字段都是必需的' });
    }

    const nodemailer = require('nodemailer');

    // 创建邮件发送器
    const transporter = nodemailer.createTransporter({
        host: smtp_host,
        port: parseInt(smtp_port),
        secure: smtp_secure === 'true',
        auth: {
            user: smtp_user,
            pass: smtp_pass
        },
        tls: {
            rejectUnauthorized: false
        }
    });

    const mailOptions = {
        from: smtp_user,
        to: test_email,
        subject: 'Minecraft面板 - 邮件配置测试',
        html: `
            <h2>邮件配置测试</h2>
            <p>这是一封来自Minecraft面板的测试邮件。</p>
            <p>如果您收到这封邮件，说明邮件配置正确。</p>
            <p>发送时间: ${new Date().toLocaleString()}</p>
        `
    };

    transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
            return res.status(500).json({ error: '邮件发送失败', details: error.message });
        }
        res.json({ success: true, message: '邮件发送成功', info });
    });
});

// 获取系统信息
router.get('/system-info', (req, res) => {
    if (!req.session.user || req.session.user.role !== 'admin') {
        return res.status(403).json({ error: '没有权限' });
    }

    const { exec } = require('child_process');
    const os = require('os');

    // 获取系统信息
    const systemInfo = {
        hostname: os.hostname(),
        platform: os.platform(),
        arch: os.arch(),
        uptime: os.uptime(),
        total_memory: os.totalmem(),
        free_memory: os.freemem(),
        cpus: os.cpus().length,
        node_version: process.version,
        panel_version: '1.0.0'
    };

    // 获取磁盘使用情况
    exec('df -h', (error, stdout, stderr) => {
        if (!error) {
            systemInfo.disk_usage = stdout;
        }

        // 获取内存使用情况
        exec('free -h', (error, stdout, stderr) => {
            if (!error) {
                systemInfo.memory_usage = stdout;
            }

            res.json({ success: true, system_info: systemInfo });
        });
    });
});

// 获取用户统计
router.get('/user-stats', (req, res) => {
    if (!req.session.user || req.session.user.role !== 'admin') {
        return res.status(403).json({ error: '没有权限' });
    }

    // 获取用户总数
    db.get('SELECT COUNT(*) as total FROM users', (err, row) => {
        if (err) {
            return res.status(500).json({ error: '获取用户统计失败' });
        }

        const totalUsers = row.total;

        // 获取活跃用户数（最近30天登录）
        db.get("SELECT COUNT(*) as active FROM users WHERE created_at >= datetime('now', '-30 days')", (err, row) => {
            if (err) {
                return res.status(500).json({ error: '获取用户统计失败' });
            }

            const activeUsers = row.active;

            // 获取管理员数量
            db.get("SELECT COUNT(*) as admins FROM users WHERE role = 'admin'", (err, row) => {
                if (err) {
                    return res.status(500).json({ error: '获取用户统计失败' });
                }

                const adminUsers = row.admin;

                // 获取服务器总数
                db.get('SELECT COUNT(*) as total FROM servers', (err, row) => {
                    if (err) {
                        return res.status(500).json({ error: '获取用户统计失败' });
                    }

                    const totalServers = row.total;

                    // 获取运行中的服务器数量
                    db.get("SELECT COUNT(*) as running FROM servers WHERE status = 'running'", (err, row) => {
                        if (err) {
                            return res.status(500).json({ error: '获取用户统计失败' });
                        }

                        const runningServers = row.running;

                        res.json({
                            success: true,
                            stats: {
                                total_users: totalUsers,
                                active_users: activeUsers,
                                admin_users: adminUsers,
                                total_servers: totalServers,
                                running_servers: runningServers
                            }
                        });
                    });
                });
            });
        });
    });
});

// 备份数据库
router.post('/backup-database', (req, res) => {
    if (!req.session.user || req.session.user.role !== 'admin') {
        return res.status(403).json({ error: '没有权限' });
    }

    const backupDir = './backups';
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
    const backupFile = `${backupDir}/database-backup-${timestamp}.sqlite`;

    // 创建备份目录
    if (!fs.existsSync(backupDir)) {
        fs.mkdirSync(backupDir, { recursive: true });
    }

    // 复制数据库文件
    fs.copyFile('./database.sqlite', backupFile, (err) => {
        if (err) {
            return res.status(500).json({ error: '备份失败' });
        }

        res.json({
            success: true,
            message: '数据库备份成功',
            backup_file: backupFile,
            backup_time: timestamp
        });
    });
});

// 获取备份列表
router.get('/backups', (req, res) => {
    if (!req.session.user || req.session.user.role !== 'admin') {
        return res.status(403).json({ error: '没有权限' });
    }

    const backupDir = './backups';

    if (!fs.existsSync(backupDir)) {
        return res.json({ success: true, backups: [] });
    }

    fs.readdir(backupDir, (err, files) => {
        if (err) {
            return res.status(500).json({ error: '获取备份列表失败' });
        }

        const backups = files
            .filter(file => file.endsWith('.sqlite'))
            .map(file => {
                const filePath = `${backupDir}/${file}`;
                const stats = fs.statSync(filePath);
                return {
                    filename: file,
                    path: filePath,
                    size: stats.size,
                    created_at: stats.birthtime
                };
            })
            .sort((a, b) => b.created_at - a.created_at);

        res.json({ success: true, backups });
    });
});

// 恢复数据库
router.post('/restore-database', (req, res) => {
    if (!req.session.user || req.session.user.role !== 'admin') {
        return res.status(403).json({ error: '没有权限' });
    }

    const { backup_file } = req.body;

    if (!backup_file) {
        return res.status(400).json({ error: '备份文件路径是必需的' });
    }

    if (!fs.existsSync(backup_file)) {
        return res.status(404).json({ error: '备份文件不存在' });
    }

    // 创建当前数据库的备份
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
    const preRestoreBackup = `./backups/pre-restore-${timestamp}.sqlite`;

    fs.copyFile('./database.sqlite', preRestoreBackup, (err) => {
        if (err) {
            return res.status(500).json({ error: '创建预恢复备份失败' });
        }

        // 恢复数据库
        fs.copyFile(backup_file, './database.sqlite', (err) => {
            if (err) {
                return res.status(500).json({ error: '恢复数据库失败' });
            }

            res.json({
                success: true,
                message: '数据库恢复成功',
                pre_restore_backup: preRestoreBackup
            });
        });
    });
});

// 清理日志
router.post('/clean-logs', (req, res) => {
    if (!req.session.user || req.session.user.role !== 'admin') {
        return res.status(403).json({ error: '没有权限' });
    }

    const { days } = req.body;
    const cleanDays = parseInt(days) || 30;

    // 这里可以添加清理日志的逻辑
    // 例如：清理旧的日志文件、数据库中的日志记录等

    res.json({
        success: true,
        message: `已清理 ${cleanDays} 天前的日志`
    });
});

module.exports = router;